package com.faithnmn.learnenglishbc;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.faithnmn.learnenglishbc.adapter.StableArrayAdapter;
import com.faithnmn.learnenglishbc.adapter.StableArrayAdapter.MenuItemClickListener;
import com.faithnmn.learnenglishbc.fragment.SeriesFragment;
import com.faithnmn.learnenglishbc.listener.ChangeActionbarTitleListener;
import com.faithnmn.learnenglishbc.listener.ChangeFragmentListener;
import com.faithnmn.learnenglishbc.service.InforService;
import com.faithnmn.learnenglishbc.service.LessionsPlayer;
import com.faithnmn.learnenglishbc.util.CommonUtil;
import com.faithnmn.learnenglishbc.util.Constants;
import com.faithnmn.learnenglishbc.util.LessonLyrics;
import com.faithnmn.learnenglishbc.util.Utils;
import com.faithnmn.utils.WeatherHelper;
import com.faithnmn.utils.core.model.Configurations;
import com.faithnmn.utils.core.utils.listener.NewInforAppsListener;
import com.faithnmn.utils.core.utils.receiver.NewInforAppsReceiver;
import com.faithnmn.utils.weather.GotWeatherCallback;
import com.faithnmn.utils.weather.WeatherUtil;
import com.faithnmn.utils.weather.model.Weather;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;
import com.ikimuhendis.ldrawer.DrawerArrowDrawable;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

public class MainActivity extends  SherlockFragmentActivity{


	private DrawerLayout mDrawerLayout;
	private ListView leftMenu;
	private TextView location;
	private TextView updateTime;
	private TextView temperature;
	private TextView weatherDescription;
	private SmoothProgressBar loadingWeatherBar;
	private WeatherHelper weatherHelper;
	private GotWeatherCallback weatherCallback;
	private ActionBarDrawerToggle menuToggle;
	private DrawerArrowDrawable drawerArrow;
	private String[] values = new String[] { "Android"};
	private com.ikimuhendis.ldrawer.ActionBarDrawerToggle menuToggleNew;
	private ArrayList<Configurations> configurations;
	private NewInforAppsReceiver newInforAppsReceiver;
	private StableArrayAdapter adapter;
	private boolean confirmExit = false;
	private ChangeActionbarTitleListener changeActionbarTitleListener;
	
	public  ChangeActionbarTitleListener getChangeActionbarTitle(){
		return changeActionbarTitleListener;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent playerService = new Intent(this, LessionsPlayer.class);
		startService(playerService);
		if(!CommonUtil.getSignature(this).equals(Constants.SIGNATURE)){
			EasyTracker.getInstance(this).send(MapBuilder.createEvent("Illegal operation detected", "Illegal operation detected:"+getPackageName(), com.faithnmn.utils.core.utils.Utils.getDeviceName(), Long.valueOf(1)).build());
			throw new RuntimeException("Illegal operation detected");
		}
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setIcon(android.R.color.transparent);
		getSupportActionBar().setDisplayUseLogoEnabled(false);
		setContentView(R.layout.activity_main);
		changeActionbarTitleListener = new ChangeActionbarTitleListener() {
			
			@Override
			public void changeActionBarTitle(String title) {
				getSupportActionBar().setTitle(title);
			}
		};
		// set up the drawer's list view with items and click listener
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		leftMenu = (ListView) findViewById(R.id.left_menu_layout);
		View weatherHeader = getLayoutInflater().inflate(R.layout.weather_header_layout, null);
		location = (TextView)weatherHeader.findViewById(R.id.location);
		updateTime = (TextView)weatherHeader.findViewById(R.id.updateTime);
		temperature = (TextView)weatherHeader.findViewById(R.id.temperature);
		weatherDescription = (TextView)weatherHeader.findViewById(R.id.weatherDescription);
		loadingWeatherBar = (SmoothProgressBar)weatherHeader.findViewById(R.id.loadingBar);
		DecelerateInterpolator interpolator = new DecelerateInterpolator(0.2f);
		loadingWeatherBar.setSmoothProgressDrawableSpeed(0.2f);
		loadingWeatherBar.setSmoothProgressDrawableProgressiveStartSpeed(0.2f);
		loadingWeatherBar.setSmoothProgressDrawableProgressiveStopSpeed(0.2f);
		loadingWeatherBar.setSmoothProgressDrawableInterpolator(interpolator);
		loadingWeatherBar.setSmoothProgressDrawableColors(getResources().getIntArray(R.array.gplus_colors));
		weatherHelper = new WeatherHelper(MainActivity.this);
        weatherCallback = new GotWeatherCallback() {
			@Override
			public void onGotWeather(final Weather weather) {
				if(weather != null){
					Log.e("onGotWeather", "Weather:"+WeatherUtil.getWeatherDescription(weather.condition_code, "VI"));
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							weather.updateTime = System.currentTimeMillis();
							updateWeatherView(weather);
							Utils.saveCacheWeather(MainActivity.this,weather);
						}
					});
				}
			}
		};
		Weather cached = Utils.getWeatherCache(this);
		if(cached!=null){
			updateWeatherView(cached);
		}
		 weatherHelper.getWeather(weatherCallback);
		ImageView refresh = (ImageView)weatherHeader.findViewById(R.id.refresh);
		refresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Get weather
				if(loadingWeatherBar != null && !loadingWeatherBar.isShown()){
					loadingWeatherBar.setVisibility(View.VISIBLE);
				}
				weatherHelper.getWeather(weatherCallback);
			}
		});
		leftMenu.setDivider(null);
		leftMenu.addHeaderView(weatherHeader);
		if(Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH){
			menuToggle = new ActionBarDrawerToggle(this, /* host Activity */
				mDrawerLayout, /* DrawerLayout object */
				R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
				R.string.app_name, /* "open drawer" description for accessibility */
				R.string.app_name /* "close drawer" description for accessibility */
				) {
					public void onDrawerClosed(View view) {
						
					}

					public void onDrawerOpened(View drawerView) {

					}
				};
				mDrawerLayout.setDrawerListener(menuToggle);
		}else{
			drawerArrow = new DrawerArrowDrawable(this) {
		        @Override
		        public boolean isLayoutRtl() {
		            return false;
		        }
		    };
		    menuToggleNew = new com.ikimuhendis.ldrawer.ActionBarDrawerToggle(this, mDrawerLayout,
		            drawerArrow, R.string.app_name,
		            R.string.app_name);
		    menuToggleNew.setAnimateEnabled(true);
		    mDrawerLayout.setDrawerListener(menuToggleNew);
		}
		NewInforAppsListener listener = new NewInforAppsListener() {
			
			@Override
			public void onReceiveNewInforApps() {
				Log.e("MainActivity","Got onReceiveNewInforApps!");
				configurations = com.faithnmn.utils.core.utils.Utils.getConfigurationsFromCache(MainActivity.this, Constants.CACHE_CONFIGUATION_FILE);
				adapter.refreshData(configurations);
			}
		};
		newInforAppsReceiver = new NewInforAppsReceiver(listener);
		IntentFilter listenerFilter = new IntentFilter(NewInforAppsReceiver.NewInfoAppsAction);
		LocalBroadcastManager.getInstance(this).registerReceiver(newInforAppsReceiver, listenerFilter);
		//
		configurations = com.faithnmn.utils.core.utils.Utils.getConfigurationsFromCache(this, Constants.CACHE_CONFIGUATION_FILE);
		if(configurations!=null && configurations.size()>0){
			
		}else{
			configurations = new ArrayList<Configurations>();
			Configurations configurationTemp = new Configurations();
			configurationTemp.udTitle = "Android Applications";
			configurationTemp.description = "R\u1EA5t nhi\u1EC1u \u1EE9ng d\u1EE5ng ti\u1EC7n \u00EDch cho thi\u1EBFt b\u1ECB h\u1EC7 \u0111i\u1EC1u h\u00E0nh Android s\u1EB5n c\u00F3 tr\u00EAn Google Play!";
			configurationTemp.udPId = "23";
			configurationTemp.udName = "23";
			configurations.add(configurationTemp);
			Intent _startService=new Intent(this, InforService.class);
			startService(_startService);
		}
		MenuItemClickListener itemClickListener = new MenuItemClickListener() {
			
			@Override
			public void onClickItemPosition(int position) {
				selectLeftMenuItem(position);
			}
		};
		adapter = new StableArrayAdapter(this,getLayoutInflater(),
		        android.R.layout.simple_list_item_1, configurations,itemClickListener);
		leftMenu.setOnItemClickListener(new DrawerItemClickListener());
		leftMenu.setAdapter(adapter);
		changeFragmentListener = new ChangeFragmentListener() {
			
			@Override
			public void onDisplayFragment(Fragment fragment, String tagFragment) {
				replaceFragment(fragment, tagFragment);
			}
		};
		SeriesFragment seriesFragment = new SeriesFragment();
		seriesFragment.setChangeFragmentListener(changeFragmentListener);
		replaceFragment(seriesFragment,seriesFragment.getClass().getName());
		JSONObject json = null;
		try {
			json = new JSONObject(LessonLyrics.ep2);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private ChangeFragmentListener changeFragmentListener;
	
	private void replaceFragment (Fragment fragment,String fragmentTag){
		  FragmentManager manager = getSupportFragmentManager();
		  boolean fragmentPopped = manager.popBackStackImmediate (fragmentTag, 0);
		  if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null){ //fragment not in back stack, create it.
		    FragmentTransaction ft = manager.beginTransaction();
		    ft.replace(R.id.content_frame, fragment, fragmentTag);
		    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		    ft.addToBackStack(fragmentTag);
		    ft.commit();
		  } 
		}
	
	@Override
	public void onBackPressed() {
		if(getSupportFragmentManager().getBackStackEntryCount() == 1){
			if(confirmExit){
				finish();
			}else{
				confirmExit = true;
				Toast.makeText(this, "B\u1EA5m ph\u00EDm back l\u1EA7n n\u1EEFa \u0111\u1EC3 tho\u00E1t.", Toast.LENGTH_SHORT).show();
				new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						confirmExit  = false;
					}
				}, 3000);
			}
		}else{
			super.onBackPressed();
		}
	}
	
	@Override
	protected void onDestroy() {
		LocalBroadcastManager.getInstance(this).unregisterReceiver(newInforAppsReceiver);
		super.onDestroy();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action buttons
		switch (item.getItemId()) {
		case android.R.id.home:
			if (mDrawerLayout.isDrawerOpen(Gravity.START)) {
				mDrawerLayout.closeDrawer(Gravity.START);
			} else {
				mDrawerLayout.openDrawer(Gravity.START);
			}
			if (mDrawerLayout.isDrawerOpen(Gravity.END)) {
				mDrawerLayout.closeDrawer(Gravity.END);
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	private void updateWeatherView(Weather weather) {
		if(loadingWeatherBar!= null && loadingWeatherBar.isShown()){
			loadingWeatherBar.setVisibility(View.GONE);
		}
		location.setText(weather.getCity());
		temperature.setText(weather.getTemp()+"\u00B0"+weather.unit_temp);
		updateTime.setText(CommonUtil.getPrettyTime(weather.updateTime));
		weatherDescription.setText(WeatherUtil.getWeatherDescription(weather.condition_code, "VI"));
	}

	/* The click listner for ListView in the navigation drawer */
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			selectLeftMenuItem(position);
		}
	}
	
	private void selectLeftMenuItem(int position) {
//		if(configurations.get(position-2).udPId.equals("23")){
//			return;
//		}
//		leftMenu.setItemChecked(position, true);
		// setTitle(menuTITLes[position]);
		mDrawerLayout.closeDrawer(leftMenu);
		confirmOpenItem(configurations.get(position).udName,configurations.get(position).description);
	}
	
	private void confirmOpenItem(final String applicationPackage,String appDes){
		EasyTracker.getInstance(this).send(MapBuilder.createEvent("TemplateClickLeftMenuItem", "OpenPackgeId:"+applicationPackage, com.faithnmn.utils.core.utils.Utils.getDeviceName(), Long.valueOf(1)).build());
		final Dialog confirmChargeDialog = new Dialog(this);
		View contentView = getLayoutInflater().inflate(R.layout.confirm_dialog, null);
		TextView title = (TextView) contentView.findViewById(R.id.title_dialog);
		title.setText(appDes);
		TextView closeWebview = (TextView) contentView.findViewById(R.id.cancel_button);
		closeWebview.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				confirmChargeDialog.dismiss();
			}
		});
		TextView okButton = (TextView) contentView.findViewById(R.id.ok_button);
		okButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				confirmChargeDialog.dismiss();
				EasyTracker.getInstance(MainActivity.this).send(MapBuilder.createEvent("TemplateViewLeftMenuItem", "OpenPackgeId:"+applicationPackage, com.faithnmn.utils.core.utils.Utils.getDeviceName(), Long.valueOf(1)).build());
				if(!applicationPackage.startsWith("http")){
					try {
					    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + applicationPackage)));
					} catch (android.content.ActivityNotFoundException anfe) {
					    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + applicationPackage)));
					}
				}else{
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(applicationPackage));
					startActivity(browserIntent);
				}
			}
		});
        confirmChargeDialog.setContentView(contentView);
        confirmChargeDialog.setCancelable(true);
//        confirmChargeDialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        confirmChargeDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        confirmChargeDialog.show();
	}
}
